package com.abing.core.utils;

import org.springframework.util.StringUtils;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * @author daifei
 * @Date 2018/4/25 17:40
 */
public class MaskUtil {
    /**
     * 手机号脱敏
     * @param mobile
     * @return
     */
    public static String maskMobile(String mobile) {
        if(StringUtils.isEmpty(mobile)) {
            return mobile;
        }
        return mobile.replaceAll("(?<=\\w{3})\\w(?=\\w{4})", "*");
    }

    /**
     * 身份证脱敏
     * @param idNo
     * @return
     */
    public static String maskIdNo(String idNo) {
        if(StringUtils.isEmpty(idNo)) {
            return idNo;
        }
        return idNo.replaceAll("(?<=\\w{6})\\w(?=\\w{4})", "*");
    }

    /**
     * 银行卡号脱敏
     * @param bankCardNo
     * @return
     */
    public static String maskBankCardNo(String bankCardNo) {
        if(StringUtils.isEmpty(bankCardNo)) {
            return bankCardNo;
        }
        String trimBankCardNo = bankCardNo.trim();
        if(trimBankCardNo.length() >= 4) {
            return trimBankCardNo.subSequence(0, 4) + "****" + trimBankCardNo.substring(trimBankCardNo.length() - 4);
        }
        else {
            return trimBankCardNo;
        }
    }

    /**
     * 姓名脱敏
     * 2字姓名第2位*号代替
     * 3字姓名中间*号代替
     * 大于等于4字姓名除了前2位，其它都用*号代替
     *
     * @param name
     * @return
     */
    public static String maskName(String name) {
        if(StringUtils.isEmpty(name)) {
            return name;
        }
        if(name.length() == 2) {
            return name.substring(0, 1) + "*";
        }
        else if(name.length() == 3) {
            return name.substring(0, 1) + "*" + name.substring(2);
        }
        else if(name.length() >= 4) {
            int number = name.length() - 2;
            StringBuilder str = new StringBuilder();
            for(int i = 0; i < number; i++) {
                str.append("*");
            }
            return name.substring(0, 2) + str.toString();
        }
        return name;
    }

    public static String maskEmail(String email) {
        if(StringUtils.isEmpty(email)) {
            return email;
        }
        int index = email.indexOf('@');
        if(index < 0) {
            return email.replaceAll("(?<=\\w{1})\\w(?=\\w{1})", "*");
        }
        if(index <= 1) {
            return "*" + email.substring(email.indexOf('@'));
        }
        if(index == 2) {
            return "**" + email.substring(email.indexOf('@'));
        }
        StringBuilder str = new StringBuilder();
        str.append(email.subSequence(0, 1));
        for(int i = 1; i + 1 < index; i++) {
            str.append("*");
        }
        str.append(email.substring(index - 1));
        return str.toString();
    }

    /**
     * 密码脱敏
     * @Author WeiXiaowei
     * @CreateDate 2019年11月14日下午3:21:08
     */
    public static String maskPwd(String pwd) {
        if(StringUtils.isEmpty(pwd)) {
            return pwd;
        }
        int len = pwd.length();
        if(len <= 2) {
            return len == 1 ? "*" : "**";
        }
        char[] chars = new char[len - 2];
        Arrays.fill(chars, '*');
        return new StringBuilder()//
            .append(pwd.charAt(0))//
            .append(chars)//
            .append(pwd.charAt(len - 1))//
            .toString();
    }

    /**
     * 实体类根据所传字段脱敏，
     * @param model 实体类
     * @param paramNameStr  需脱敏字段 ,分割
     * @param <T>
     * @return
     */
    private static <T> T fieldHide(T model, String paramNameStr){
        Set<String> paramSet = new HashSet<>(8);
        String[] params = paramNameStr.split(",");
        Arrays.stream(params).forEach(obj -> paramSet.add(obj.trim().toLowerCase()));

        StringBuffer msg = new StringBuffer();
        //获取实体类的所有字段
        Field[] fields = model.getClass().getDeclaredFields();
        Arrays.stream(fields).forEach(obj -> {
            obj.setAccessible(true);

            if (paramSet.contains(obj.getName().trim().toLowerCase())){
                try {
                    Object value=obj.get(model);
                    String name=obj.getName();
                    //获取set方法名
                    String setMethodName = "set"+name.substring(0, 1).toUpperCase()
                            +name.replaceFirst("\\w", "");
                    //得到get方法的Method对象,带参数
                    Method setMethod = model.getClass().getDeclaredMethod(setMethodName,obj.getType());
                    setMethod.setAccessible(true);
                    //赋值
                    setMethod.invoke(model, getValue(String.valueOf(value).trim()));
                } catch (IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        });
        return model;
    }

    /**
     * 设置需要脱敏的字段
     * @return
     */
    private static String getParam(){
        String param="telephone";
        return param;
    }
    /**
     * 实体类根据所传字段脱敏，
     * @param model 实体类
     * @param <T>
     * @return
     */
    private static <T> T fieldHide(T model){
        return fieldHide(model,getParam());
    }
    private static String getValue(String value){
        if(StringUtils.isEmpty(value)) {
            return value;
        }
        //姓名脱敏
        if (value.length()<11){
            return maskName(value);
        }
        //手机号脱敏
        if (value.length()==11){
            return maskMobile(value);
        }
        return maskIdNo(value);
    }
    public static void main(String[] args) {
//        TLogVO mobileRequest=new TLogVO();
//        mobileRequest.setId("1");
//        mobileRequest.setOperator("李三");
//        mobileRequest.setMethodName("17321436171");
//        mobileRequest.setFilterLevel("370831198411146235");
//        String field="operator,methodName,filterLevel";
//        System.out.println(fieldHide(mobileRequest,field).toString());
    }





//    public static void main(String[] args) {
//        System.out.println(maskIdNo("173214367781"));
//        System.out.println(maskBankCardNo("17321438871"));
//        System.out.println(maskMobile("1732143"));
//        System.out.println(maskName("张三"));
//        System.out.println(maskName("李小二"));
//        System.out.println(maskName("诸葛孔明"));
//        System.out.println(maskName("诸葛孔明孔明孔明"));
//        System.out.println(maskEmail("123232qq.com"));
//        System.out.println(maskEmail("@qq.com"));
//        System.out.println(maskEmail("5@qq.com"));
//        System.out.println(maskEmail("55@qq.com"));
//        System.out.println(maskEmail("12345678901234567@qq.com"));
//        System.out.println(maskPwd("12"));
//        System.out.println(maskPwd("sdfsfds"));
//    }
}
